﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnitOfWorkCore.Domain.Abstractions;
using UnitOfWorkCore.Infrastructure.Extensions;

namespace UnitOfWorkCore.Infrastructure
{
    public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
    {

        private readonly TDbContext _Mddb;
        private readonly IMediator _mediator;

        public UnitOfWork(TDbContext context, IMediator mediator)
        {
            _Mddb = context ?? throw new ArgumentNullException(nameof(context));
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            await _mediator.DispatchDomainEventsAsync(_Mddb);
            // 调用基类的 SaveChangesAsync 方法，将更改保存到数据库
            return await _Mddb.SaveChangesAsync(cancellationToken);
        }

        public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
        {
            await _Mddb.SaveChangesAsync();
            // 默认为true，如果报错，不在这里包裹异常
            return true;
        }

        //public void Dispose() => this.Dispose();

    }
}
